package hars

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soon/catch"
	"soon/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")

	title := c.PostForm("title")
	if name == "" || title == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不嫩为空",
			"data": nil,
		})
		return
	}
	data := models.Soon{
		Name:  name,
		Title: title,
	}

	models.DB.Create(&data)

	redis_key := "soons" + strconv.Itoa(int(data.ID))
	var soons models.Soon
	models.DB.Where("id = ?", data.ID).First(&soons)
	jsondata, _ := json.Marshal(&soons)
	catch.Rdb.Set(catch.Ctx, redis_key, jsondata, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?", id).Delete(&models.Soon{})
	redis_key := "soons" + id
	catch.Rdb.Get(catch.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
		"data": nil,
	})
	return
}
func List(c *gin.Context) {
	var soons []models.Soon

	redis_key := "redis_key"
	catchcount, _ := catch.Rdb.Get(catch.Ctx, redis_key).Result()
	if catchcount == "" {
		models.DB.Find(&soons)
		jsondata, _ := json.Marshal(&soons)
		catch.Rdb.Set(catch.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catchcount), &soons)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": soons,
	})
	return
}
